package prj.carmap.mobile.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

/**
 * 文件工具类
 *
 */
public class FileUtil {
	private static final String TAG = "FileUtil";

	public static final int DOWNLOAD_FAILED = -1;
	public static final int DOWNLOAD_SUCCESS = 1;
	public static final int SDCARD_NOT_EXIST = 2;
	public static final int FILE_EXIST = 3;

	public static final String sdcard_dir = Environment.getExternalStorageDirectory().getAbsolutePath();

	public final static String FILE_DIR = sdcard_dir + "/CarMap";
	public final static String HEADER_FILE_DIR = FILE_DIR + "/headers";
	public final static String ATTACHMENT_FIEL_DIR = FILE_DIR + "/download";

	public final static FileUtil INSTANCE = new FileUtil();

	private FileUtil() {
	}

	/**
	 * 下载图片到SD卡
	 * @param fileName
	 * @param bitmap
	 * @return
	 */
	public synchronized int downLoadpicToSdcard(String fileName, Bitmap bitmap)
	{
		if (!SdcardExist())
		{
			return FileUtil.SDCARD_NOT_EXIST;
		}

		File file = new File(ATTACHMENT_FIEL_DIR + "/" + fileName + ".jpg");

		if (IsFileExist(file))
		{
			return FileUtil.FILE_EXIST;
		}


		FileOutputStream outputStream = null;
		try {
			file.createNewFile();
			outputStream = new FileOutputStream(file);
			bitmap.compress(CompressFormat.JPEG, 50, outputStream);
			return FileUtil.DOWNLOAD_SUCCESS;
		}
		catch (Exception e) {
			e.printStackTrace();
			return FileUtil.DOWNLOAD_FAILED;
		}
		finally {
			if (outputStream != null)
			{
				try {
					outputStream.close();
				}
				catch (Exception e2) {
					return FileUtil.DOWNLOAD_FAILED;
				}
			}
		}
	}

	/**
	 * 存储头像到SD卡
	 * @param bitmap
	 * @param avater_name
	 * @return
	 */
	public synchronized int storeHeaderInSdcrad(Bitmap bitmap, String avater_name) {
		if (!SdcardExist()) {
			return SDCARD_NOT_EXIST;
		}

		File file = new File(HEADER_FILE_DIR + "/" + avater_name);
		if (IsFileExist(file)) {
			return FILE_EXIST;
		}

		FileOutputStream fileOutputStream = null;
		try
		{
			file.createNewFile();
			fileOutputStream = new FileOutputStream(file);
			bitmap.compress(CompressFormat.JPEG, 50, fileOutputStream);

			return DOWNLOAD_SUCCESS;
		}
		catch (Exception e) {
			return DOWNLOAD_FAILED;
		}
		finally {
			if (fileOutputStream != null) {
				try {
					fileOutputStream.flush();
					fileOutputStream.close();
				}
				catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 返回附件文件
	 * @param fileName
	 * @return
	 */
	public File GetAttachmentFile(String fileName) {
		File file = new File(ATTACHMENT_FIEL_DIR + "/" + fileName);
		return file;
	}

	public Intent GetOpenFileTypeIntent(String FileName)
	{
		Intent intent = new Intent();
		intent.setAction(android.content.Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(new File(sdcard_dir + "/" + FileName)), checkType(FileName));

		return intent;
	}

	/**
	 * 根据文件名判断文件类型
	 * @param fileName
	 * @return
	 */
	public String checkType(String fileName)
	{
		int dotIndex = fileName.lastIndexOf('.');
		if (dotIndex < 0)
		{
			return FileType.OTHER;
		}

		String end = fileName.substring(dotIndex + 1, fileName.length()).toLowerCase();

		if (checkPostFixOffFile(end, FileType.IMAGES))
		{
			return FileType.IMAGE;
		}
		else if (checkPostFixOffFile(end, FileType.AUDIOS))
		{
			return FileType.AUDIO;
		}
		else if (checkPostFixOffFile(end, FileType.VIDEOS))
		{
			return FileType.VIDEO;
		}
		else if (checkPostFixOffFile(end, FileType.TEXTS))
		{
			return FileType.TEXT;
		}
		else if (checkPostFixOffFile(end, FileType.APPS))
		{
			return FileType.APP;
		}
		else {
			return FileType.OTHER;
		}
	}

	private boolean checkPostFixOffFile(String end, String[] postFixFile) {
		for (String postFix : postFixFile)
		{
			if (end.equals(postFix))
			{
				return true;
			}
		}

		return false;
	}


	public boolean IsFileExist(File file) {
		return file.exists() && file.isFile();
	}


	public boolean SdcardExist() {
		return Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
	}

	public void CheckAppDirectroy() {
		if (SdcardExist()) {
			CreatFileDir(FILE_DIR);
			CreatFileDir(ATTACHMENT_FIEL_DIR);
			CreatFileDir(HEADER_FILE_DIR);
		}
	}

	private void CreatFileDir(String fileDir) {
		File file = new File(fileDir);
		if (!file.exists() || !file.isDirectory()) {
			file.mkdir();
		}
	}

	public boolean isEmpty(String string) {
		return string == null || TextUtils.isEmpty(string) || string.equals("null");
	}

	/**
	 * 获取缓存文件
	 * @param imageUri
	 * @return
	 */
	public static File getCacheFile(String imageUri) {
		File cacheFile = null;
		try
		{
			if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
			{
				File sdCardDir = Environment.getExternalStorageDirectory();
				String fileName = getFileName(imageUri);
				File dir = new File(sdCardDir.getCanonicalPath() + "/carmap/image/");
				if (!dir.exists()) {
					dir.mkdirs();
				}
				cacheFile = new File(dir, fileName);
				Log.i(TAG, "exists:" + cacheFile.exists() + ",dir:" + dir + ",file:" + fileName);
			}
		}
		catch (IOException e)
		{
			e.printStackTrace();
			Log.e(TAG, "getCacheFileError:" + e.getMessage());
		}

		return cacheFile;
	}

	public static String getFileName(String path) {
		int index = path.lastIndexOf("/");
		return path.substring(index + 1);
	}

}
